/**
 * Copyright (c) 2013 An Yaming,  All Rights Reserved
 */
package so.shanku.essential.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonMapOrListJsonMap2JsonUtil;
import net.tsz.afinal.json.JsonParseHelper;
import com.google.gson.Gson;
import net.tsz.afinal.annotation.view.ViewInject;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.ShopAddOrderProductAdapter;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.*;
import so.shanku.essential.view.ListViewNoScroll;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tanghuan
 * @ClassName: ShoppingAddOrderActivity
 * @Description: TODO(填写订单类)
 * @date 2014年12月3日 下午7:51:44
 */
public class ShopAddOrderActivity extends BaseUIActivity {
    /**
     * 收货人布局
     */
    @ViewInject(id = R.id.s_a_o_ll_shouhuorenxinxi, click = "selectShouHuoRan")
    private LinearLayout ll_shouhuoren;
    /**
     * 收货人
     */
    @ViewInject(id = R.id.s_a_o_tv_shouhuoren)
    private TextView tv_shouhuren;
    /**
     * 收货人电话
     */
    @ViewInject(id = R.id.s_a_o_tv_phone)
    private TextView tv_shouhuren_dianhua;
    /**
     * 收货人地址
     */
    @ViewInject(id = R.id.s_a_o_tv_address)
    private TextView tv_shouhuren_dizhi;
    /**
     * 支付和配送的点击选择
     */
    @ViewInject(id = R.id.s_a_o_ll_payandsend, click = "payandsend")
    private LinearLayout ll_payandsend;
    /**
     * 支付信息方式
     */
    @ViewInject(id = R.id.s_a_o_tv_payway)
    private TextView tv_zhifu;


    /**
     * 备注
     */
    @ViewInject(id = R.id.s_a_o_et_note)
    private EditText et_note;

    /**
     * 普通发票展示信息
     */
    @ViewInject(id = R.id.s_a_o_tv_youhuiquan, click = "coupon_click")
    private TextView tv_coupon;
    /**
     * 返回购物车修改
     */
    @ViewInject(id = R.id.s_a_o_tv_backshoppingcart, click = "goShoppingCart")
    private TextView tv_goshoppingcart;
    /**
     * 返回购物车修改
     */
    @ViewInject(id = R.id.s_a_o_lvns_prolist)
    private ListViewNoScroll lvns_proList;
    /**
     * 商品金额
     */
    @ViewInject(id = R.id.s_a_o_tv_shangpinprice)
    private TextView tv_qian_shangpin;
    /**
     * 运费
     */
    @ViewInject(id = R.id.s_a_o_tv_yunfei)
    private TextView tv_qian_yunfei;
    /**
     * 活动优惠
     */
    @ViewInject(id = R.id.s_a_o_tv_fanxian)
    private TextView tv_qian_fanxian;

    /**
     * 优惠券
     */
    @ViewInject(id = R.id.s_a_o_tv_privilege_discount)
    private TextView tv_privilege_discount;
    /**
     * 应付总额
     */
    @ViewInject(id = R.id.s_a_o_tv_tatalpay)
    private TextView tv_qian_yingfuzonge;
    /**
     * 应付金额
     */
    @ViewInject(id = R.id.s_a_o_tv_totalmoney)
    private TextView tv_qian_yingfujine;

    /**
     * 提交订单
     */
    @ViewInject(id = R.id.s_a_o_ib_commitorder, click = "commit_order_click")
    private Button ib_tijiao_dingdan;


    //应付金额
    private double actualPayPrice;
    /**
     * 由购物车传入的订单商品信息 json格式
     */
    private String selectProJson;
    /**
     * 由购物车传入的订单商品信息
     */
    private List<JsonMap<String, Object>> selectProduct;
    /**
     * 本次订单的收货信息的id 支付信息的id
     */
    private String addressId = "0", payId = "1";
    /**
     * 使用优惠券的id
     */
    private String couponid = "0";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_add_order);
        setCenter_title(R.string.shopping_add_order_title);
        Intent intent = getIntent();
        String zongjia = intent.getStringExtra(ExtraKeys.Key_Msg1);
        selectProJson = intent.getStringExtra(ExtraKeys.Key_Msg2);
        selectProduct = JsonParseHelper.getList_JsonMap(selectProJson);

        setAdapter_porList();
        tv_qian_shangpin.setText(StringUtil.getFormatMoneyWithSignMust(zongjia));
        tv_qian_fanxian.setText(StringUtil.getFormatMoneyWithSignMust("0"));
        tv_qian_yunfei.setText(StringUtil.getFormatMoneyWithSignMust("0"));
        tv_qian_yingfujine.setText(StringUtil.getFormatMoneyWithSignMust(zongjia));
        tv_qian_yingfuzonge.setText(StringUtil.getFormatMoneyWithSignMust(zongjia));
        tv_privilege_discount.setText(StringUtil.getFormatMoneyWithSignMust("0"));

        getData_getDefInfo();

        registerReceiver(broadcastReceiver, new IntentFilter(Constant.ACT_PAY_OVER));
//		et_fapiao_taitou.addTextChangedListener(editTextContentChangeListener);
//		et_note.addTextChangedListener(editTextContentChangeListener);
//		jifen_ed.addTextChangedListener(editTextContentChangeListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mContext.setResult(RESULT_OK);
            mContext.finish();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == request_changeAddress) {
                String consignee = data.getStringExtra(ExtraKeys.Key_Msg1);
                String phone = data.getStringExtra(ExtraKeys.Key_Msg2);
                String receiptAddress = data.getStringExtra(ExtraKeys.Key_Msg3);
                addressId = data.getStringExtra(ExtraKeys.Key_Msg4);
                cancelCoupon(1);
                flushShouHuoRen(consignee, phone, receiptAddress);
            } else if (requestCode == request_payType) {
                // flushpayandsend(JsonParseHelper.getJsonMap(data
                // .getStringExtra(ExtraKeys.Key_Msg1)));
                String zhifu = data.getStringExtra(ExtraKeys.Key_Msg1);
                payId = data.getStringExtra(ExtraKeys.Key_Msg2);

                flushpayandsend(zhifu);
            } else if (requestCode == request_selectCoupon) {
//                String Price = data.getStringExtra(ExtraKeys.Key_Msg1);
//                if (Price != null) {
//                    actualPayPrice = Double.valueOf(
//                            data.getStringExtra(ExtraKeys.Key_Msg1))
//                            .doubleValue();
//                    double Coupon = Double.valueOf(
//                            data.getStringExtra(ExtraKeys.Key_Msg2))
//                            .doubleValue();
                couponid = data.getStringExtra(ExtraKeys.Key_Msg3);
                cancelCoupon(2);
                //flushJieSuanqingdan(actualPayPrice, Coupon);
                // }

            }
        }
        if (requestCode == commit_request) {
            setResult(RESULT_OK);
            finish();
        }

    }

    private void flushBottomView(JsonMap jsonMap) {
        actualPayPrice = jsonMap.getDouble("actualPayPrice");
        //tv_privilege_discount.setText(StringUtil.getFormatMoneyWithSignMust(jsonMap.getStringNoNull("CouponDiscountMoney")));
        tv_qian_yingfuzonge.setText(StringUtil.getFormatMoneyWithSignMust(actualPayPrice));
        tv_qian_yingfujine.setText(StringUtil.getFormatMoneyWithSignMust(actualPayPrice));
        tv_qian_yunfei.setText(StringUtil.getFormatMoneyWithSignMust(jsonMap.getStringNoNull("FreightPrice")));
        //tv_qian_fanxian.setText(StringUtil.getFormatMoneyWithSignMust(jsonMap.getStringNoNull("OrderEventDiscountMoney")));
    }

    /**
     * 刷新结算清单  取消优惠券
     *
     * @param data
     */
    private void flushJieSuanqingdan(JsonMap<String, Object> data) {
        actualPayPrice = Double.valueOf(
                data.getStringNoNull("actualPayPrice", "0")).doubleValue();
        tv_privilege_discount.setText(StringUtil.getFormatMoneyWithSignMust(data.getStringNoNull("couponDiscountMoney", "0")));
        tv_qian_yingfuzonge.setText(StringUtil.getFormatMoneyWithSignMust(actualPayPrice));
        tv_qian_yingfujine.setText(StringUtil.getFormatMoneyWithSignMust(actualPayPrice));
        if (couponid.equals("0")) {
            tv_coupon.setText(R.string.cancel_rivilege);
        } else {
            tv_coupon.setText(R.string.discount_coupon);
            couponid = "0";
        }

    }


    /**
     * 刷新获取到的默认信息
     */
    private void flushDefInfo(JsonMap<String, Object> data) {
        JsonMap<String, Object> priceInfo = data.getJsonMap("priceInfo");

        // 修改 订单显示
        actualPayPrice = Double.valueOf(priceInfo.getStringNoNull("actualPayPrice", "0")).doubleValue();

        tv_qian_shangpin.setText(StringUtil.getFormatMoneyWithSignMust(priceInfo.getStringNoNull("productPrice", "0")));
        tv_qian_fanxian.setText(StringUtil.getFormatMoneyWithSignMust(priceInfo.getStringNoNull("activityDiscountMoney", "0")));
        tv_qian_yunfei.setText(StringUtil.getFormatMoneyWithSignMust(priceInfo.getStringNoNull("freightPrice", "0")));
        tv_privilege_discount.setText(StringUtil.getFormatMoneyWithSignMust(0));
        tv_qian_yingfuzonge.setText(StringUtil.getFormatMoneyWithSignMust(actualPayPrice));
        tv_qian_yingfujine.setText(StringUtil.getFormatMoneyWithSignMust(actualPayPrice));

        // end
        JsonMap<String, Object> shouhuorenInfo = data
                .getJsonMap("receiptInfo");
        flushShouHuoRen(shouhuorenInfo.getStringNoNull("consignee"),
                shouhuorenInfo.getStringNoNull("phone"),
                shouhuorenInfo.getStringNoNull("receiptAddress"));
        addressId = shouhuorenInfo.getStringNoNull("addressId");

        JsonMap<String, Object> zhifuInfo = data.getJsonMap("payType");
        flushpayandsend(zhifuInfo.getStringNoNull("payName"));
        payId = zhifuInfo.getStringNoNull("payId");

    }

    /**
     * 刷新收货人信息
     */
    private void flushShouHuoRen(String shr, String dh, String dz) {
        tv_shouhuren.setText(shr);
        tv_shouhuren_dianhua.setText(dh);
        tv_shouhuren_dizhi.setText(dz);
    }

    /**
     * 刷新支付和配送信息
     */
    private void flushpayandsend(String info) {
        tv_zhifu.setText(info);
    }

    private int commit_request = 100;

    /**
     * 去生成订单页面
     */
    private void goCommited(JsonMap<String, Object> order) {
        LogUtil.d(TAG, "startPay");
        toast.showToast(R.string.order_create_success);
        JsonMapOrListJsonMap2JsonUtil<String, Object> util = new JsonMapOrListJsonMap2JsonUtil<String, Object>();
        Intent intent = new Intent(this, CommitOrderActivity.class);
        intent.putExtra(ExtraKeys.Key_Msg1, 3);
        intent.putExtra(ExtraKeys.Key_Msg2, util.map2Json(order));
        startActivityForResult(intent, commit_request);
    }

    /**
     * 为已选定的商品设定数据源
     */
    private void setAdapter_porList() {
        ShopAddOrderProductAdapter adapter = new ShopAddOrderProductAdapter(this, selectProduct);
        lvns_proList.setAdapter(adapter);

    }

    /**
     * 去选择收货信息
     */
    public void selectShouHuoRan(View v) {
        Intent intent = new Intent(this, UserRecipientActivity.class);
        intent.putExtra(ExtraKeys.Key_Msg1, addressId);
        startActivityForResult(intent, request_changeAddress);
    }

    int request_changeAddress = 1;
    int request_payType = 2;
    int request_selectCoupon = 3;

    /**
     * 去选择支付和配送信息
     */
    public void payandsend(View v) {
        Intent intent = new Intent(this, PayMethodActivity.class);
        intent.putExtra(ExtraKeys.Key_Msg1, 1);
        startActivityForResult(intent, request_payType);
    }

    /**
     * 返回购物车修改
     */
    public void goShoppingCart(View v) {
        this.finish();
    }

    /**
     * 提交订单
     */
    public void commit_order_click(View v) {
        // this.finish();
        if (TextUtils.isEmpty(addressId) || TextUtils.isEmpty(payId)) {
            //toast.showToast(R.string.shopping_add_order_addressorpayisnull);
            toast.showToast(R.string.shopping_add_order_payisnull);
            return;
        }
        getData_tijiao("");
    }

    /**
     * 调用服务器提交订单
     */
    private void getData_tijiao( String fapiaotaitou) {
        loadingToast.show();
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("userId", Utils.getUserId(mContext));
        params.put("addressId", addressId);
        params.put("payId", payId);
        params.put("shoppingCartList", selectProduct);
        params.put("couponItemId", couponid);
        params.put("remark", et_note.getText().toString());

        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_shoppingAddOrderInformation);
        queue.setCallBack(callBack);
        queue.setParamsNoJson(params);
        queue.setWhat(GetDataConfing.What_shoppingAddOrderInformation);
        getDataUtil.getData(queue);
    }

    /**
     * 通知其他页面 购物车数量改变
     */
    private void sendShopCartNumChangeBroadCast() {
        sendBroadcast(new Intent(Constant.ACAT_SHOPCARTNUMCHANGE));
    }

    /**
     * 获取填写信息的默认信息
     */
    private void getData_getDefInfo() {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();

        params.put("userId", Utils.getUserId(this));
        params.put("shoppingCartList", selectProduct);
//		int addressIdInt = 0;
//		try {
//			addressIdInt = Integer.parseInt(addressId);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//
//		params.put("addressId", addressIdInt);
//		int couponidInt = 0;
//		try {
//			couponidInt = Integer.parseInt(couponid);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//
//		params.put("couponItemId", couponidInt);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_shoppingEditOrderInformation);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_shoppingEditOrderInformation);
        queue.setParamsNoJson(params);

        getDataUtil.getData(queue);
    }

    private final int what_tijiao = 1;
    private final int what_cancelcoupon = 3;
    private final int what_getJifen = 4;//获取优惠的金额
    private final int what_changeAddress = 5;//更换地址
    /**
     * 与服务器通信的回调
     */
    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {

        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isOkAndCodeIsNot1(
                        mContext, entity.getInfo())) {
                    if (GetDataConfing.What_shoppingAddOrderInformation == entity.what) {

                        JsonMap<String, Object> orderdata = JsonParseHelper
                                .getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        if (orderdata.size() == 0) {
                            ShowGetDataError
                                    .showNetError(mContext);
                        } else {
                            orderdata.put("payId", payId);
                            String proListStr = "";
                            for (JsonMap<String, Object> jsonMap : selectProduct) {
                                proListStr += jsonMap.getStringNoNull("productName") + ",";
                            }
                            orderdata.put("productName", proListStr);
                            orderdata.put("actualPayPrice", actualPayPrice);
                            orderdata.put("payId", payId);
                            // sendShopCartNumChangeBroadCast();
                            goCommited(orderdata);
                        }
                    } else if (GetDataConfing.What_shoppingEditOrderInformation == entity.what) {
                        flushDefInfo(JsonParseHelper.getJsonMap_JsonMap(
                                entity.getInfo(), JsonKeys.Key_Info));

                    } else if (what_cancelcoupon == entity.what) {

                        JsonMap<String, Object> info = JsonParseHelper
                                .getJsonMap_JsonMap(entity.getInfo(),
                                        JsonKeys.Key_Info);
                        flushJieSuanqingdan(info);

                    } else if (what_changeAddress == entity.getWhat()) {

                        JsonMap<String, Object> info = JsonParseHelper
                                .getJsonMap_JsonMap(entity.getInfo(),
                                        JsonKeys.Key_Info);
                        flushBottomView(info);
                    }
                }
            } else {
                ShowGetDataError.showNetError(mContext);
            }
            loadingToast.dismiss();
        }
    };

    /**
     * 去选择优惠券
     */
    public void coupon_click(View v) {
        if (couponid.equals("0")) {
            //JsonMapOrListJsonMap2JsonUtil<String, Object> util = new JsonMapOrListJsonMap2JsonUtil<String, Object>();
            Intent intent = new Intent(this, ShoppingRivilegeActivity.class);
            intent.putExtra(ExtraKeys.Key_Msg2, selectProJson);
            intent.putExtra(ExtraKeys.Key_Msg3, TextUtils.isEmpty(addressId) ? "0" : addressId);
            startActivityForResult(intent, request_selectCoupon);
        } else {
            cancelCoupon(0);
        }
    }

    /**
     * 修改地址,取消优惠券
     *
     * @param type 类型 l
     */
    private void cancelCoupon(int type) {
        loadingToast.show();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", Utils.getUserId(mContext));
        params.put("shoppingCartList", selectProduct);
        if (type == 0) {
            params.put("couponItemId", "0");
        } else if (type == 1) {
            couponid = TextUtils.isEmpty(couponid) ? "0" : couponid;
            params.put("couponItemId", couponid);
        } else if (type == 2) {
            params.put("couponItemId", couponid);
        }

        addressId = TextUtils.isEmpty(addressId) ? "0" : addressId;
        params.put("addressId", addressId);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_shoppingUsedCoupon);
        queue.setCallBack(callBack);
        queue.setParamsNoJson(params);
        if (type == 0) {
            queue.setWhat(what_cancelcoupon);
        } else if (type == 1) {
            queue.setWhat(what_changeAddress);
        } else if (type == 2) {
            queue.setWhat(what_cancelcoupon);
        }
        getDataUtil.getData(queue);
    }

}
